﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EKETEAM.FrameWork;
using EKETEAM.Data;
using EKETEAM.aliyun;

using LitJson;

namespace eFrameWork.Plugins
{
    public partial class DingTalkScanLogin : System.Web.UI.Page
    {
        public string UserArea = "Application";
        eUser user;
        string redirectUrl = "";
        public string fromURL = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            fromURL = eParameters.QueryString("fromURL");
            string area = eParameters.QueryString("area");
            if (Request.QueryString["mode"] != null)
            {
                if (area.Length>0 && fromURL.Length > 0)
                {
                    fromURL += (fromURL.IndexOf("?") == -1 ? "?" : "&") + "area=" + area;
                }
                return;
            }
         
            if( eParameters.QueryString("state").Length>0) fromURL = eParameters.QueryString("state");
            if (fromURL.Length == 0) fromURL = "Default.aspx";
            redirectUrl = HttpUtility.UrlEncode(Request.Url.Path() + Request.Url.File());          
            string _fromURL = HttpUtility.UrlDecode(fromURL);
            string code = eParameters.QueryString("code");
            if (code.Length == 0) return;
            //eBase.Writeln(code);
            //eBase.AppendLog(code);
            if (fromURL.getQuery("area").Length > 0)
            {
                UserArea = fromURL.getQuery("area");
                fromURL = fromURL.removeQuery("area");
            }
            user = new eUser(UserArea);
            JsonData jd = DingTalkHelper.getUserByCode(code);
            if (!jd.Contains("user_info"))
            {
                eBase.Writeln(jd.ToJson());
                eBase.End();
            }
            string unionid = jd["user_info"]["unionid"].ToString();
            jd = DingTalkHelper.getUserByUnionid(unionid);
            string userid = jd["result"]["userid"].ToString();
            jd = DingTalkHelper.getUserByUserID(userid);

            if (_fromURL.ToLower().StartsWith("http"))
            {
                string[] arr = _fromURL.Split("/".ToCharArray());
                string host = arr[2].ToLower();
                if (eBase.DingTalkAccount.getValue("ReverseProxy").ToLower().IndexOf(host) > -1 || Request.Url.Host.ToLower()==host)
                {
                    //eBase.AppendLog(jd.ToJson());
                    string _base64 = Base64.Encode(jd.ToJson());
                    _fromURL = _fromURL.addQuery("data", _base64);
                    Response.Redirect(_fromURL, true);
                }
                eBase.End();
            }

            DataTable tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where (dduserid='" + userid + "'" + (unionid.Length > 0 ? " or ddunionid='" + unionid + "'" : "") + ") and delTag=0 order by addTime");
            if (tb.Rows.Count > 0)
            {
                if (tb.Rows[0]["Active"].ToString() == "False")
                {
                    Response.Write("登录失败,用户信息已停用!");
                    Response.End();
                }
                user = new eUser(UserArea);
                eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                eFHelper.UserLoginLog(user); //用户登录日志
                //Response.Redirect(HttpUtility.UrlDecode(fromURL), true);
                Response.Write("<script>parent.document.location.href='" + HttpUtility.UrlDecode(fromURL) + "';</script>");
                Response.End();
            }
            else
            {
                Response.Write("登录失败!");
                Response.End();
            }
        }
    }
}